<template>
  <div class="login-wrap">
    <div class="login-title">考务管理系统</div>
    <el-form label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm login-container">
     <img class="gmu_logo" src="../../assets/images/logo.png">
      <h3 class="title">用户登录</h3>
      <el-form-item prop="username">
        <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码" show-password></el-input>
      </el-form-item>
      <el-select v-model="ruleForm.usertype" placeholder="账号类型" style="margin-bottom:20px">
      <el-option
        v-for="item in options"
        :key="item.usertype"
        :label="item.label"
        :value="item.usertype">
      </el-option>
    </el-select>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="loginCode">
            <el-input type="text" v-model="loginCode" maxlength="4" auto-complete="off" placeholder="验证码" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10" class="code">
        <judge-code @getCode="getCode"></judge-code>
        </el-col>
      </el-row>
      <el-row>
            <el-checkbox class="remember" v-model="rememberpwd">记住密码</el-checkbox>
            <el-button class="registered" type="success" round  @click="handleEdit('注册')">注册</el-button>
            <el-button class="forget" type="text" @click="handleEdit('重置')">忘了密码？</el-button>
      </el-row>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click="submitForm('ruleForm')" >登录</el-button>
      </el-form-item>
    </el-form>

 <!-- 注册界面 -->
    <el-dialog :title="title" :visible.sync="stuFormVisible" width="25%" @click="closeDialog">
      <el-form label-width="102px" :model="stuForm" :rules="rules" ref="stuForm">
        <el-form-item label="您的身份证" prop="sCardNo">
          <el-input size="small" v-model="stuForm.sCardNo" auto-complete="off" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="证件类型" prop="sCardType">
          <el-select v-model="stuForm.sCardType" placeholder="">
           <el-option
             v-for="item in cardOptions"
             :key="item.value"
             :label="item.label"
             :value="item.value">
           </el-option>
           </el-select>
        </el-form-item>
         <el-form-item :label="form_label" prop="sPassword">
          <el-input type="password" size="small" v-model="stuForm.sPassword" auto-complete="off" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rStuPassword">
          <el-input type="password" size="small" v-model="stuForm.rStuPassword" auto-complete="off" placeholder="" ></el-input>
        </el-form-item>
         <el-form-item label="您的邮箱" prop="sUsername">
           <el-input size="small" v-model="stuForm.sUsername" auto-complete="off" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="输入验证码" prop="code">
        <el-row>
          <el-col :span="12">
            <el-input size="small" v-model="stuForm.code" auto-complete="off" placeholder=""></el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="info" class="getJudgeCode" @click="getJudgeCode(stuForm)" :disabled="disabled" :model="buttomValue" >{{buttomValue}}</el-button>
          </el-col>
        </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitStuForm('stuForm')" :model="method">{{method}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import JudgeCode from '@/components/Login/JudgeCode.vue'
import { login, getCode, getAccount } from '../../api/userOpe'
import { setStore, getStore, removeStore } from '../../util/util'

export default {
  name: 'login',
  components: {
    JudgeCode
  },
  data () {
    return {
      // 判断 dialog 当前操作时注册还是找回密码
      title: '注册账号',
      // 提交表单按钮类型
      method: '注册',
      // 注册页面的显示，默认否
      stuFormVisible: false,
      // 是显示加载
      loading: false,
      // 记住密码
      rememberpwd: false,
      // 父传来的 正确验证
      corCode: [],

      // 存放登入输入的验证码
      loginCode: '',

      // 发送验证码按钮的状态
      disabled: false,

      // 获取验证码按钮点击 value 发送改变

      buttomValue: '获取邮箱验证码',

      // 验证码获取倒计时时间
      countdown: 0,
      // 注册找回label切换
      form_label: '',
      // 学生忘记密码与注册 表单数据
      stuForm: {
        sCardNo: '',
        sCardType: '',
        sUsername: '',
        sPassword: '',
        rStuPassword: '',
        status: '',
        code: ''
      },
      // 判断账号密码是输入的还是store里取的
      isFromStore: false,
      // 证件类型选择器数据
      cardOptions: [{
        value: '身份证',
        label: '身份证'
      }, {
        value: '护照',
        label: '护照'
      }],
      ruleForm: {
        // username和password默认为空
        username: '',
        password: '',
        usertype: ''
      },
      // rules前端验证
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        sCardNo: [{ required: true, message: '请输入您的身份证', trigger: 'blur' }],
        sCardType: [{ required: true, message: '请选择证件类型', trigger: 'blur' }],
        sUsername: [{ required: true, message: '请输入您的邮箱', trigger: 'blur' }],
        sPassword: [{ required: true, message: '请输入您的密码', trigger: 'blur' }],
        rStuPassword: [{ required: true, message: '请再次输入您的密码', trigger: 'blur' }]
      },
      options: [{
        usertype: '1',
        label: '学生'
      },
      {
        usertype: '2',
        label: '管理员'
      }]
    }
  },
  created () {
    // 网页已经创建完成之后被调用
    this.getUserPwd()
  },
  methods: {
    // 子组件传来验证码，并保存至父组件稍后验证
    getCode (data) {
      this.corCode = data
      // console.log(this.corCode)
    },
    // 获取 用户名 密码
    getUserPwd () {
      if (getStore('user') !== null && getStore('password') !== null) {
        this.ruleForm.username = getStore('user')
        this.ruleForm.password = getStore('password')
        this.isFromStore = true
      } else {
        this.isFromStore = false
      }
    },
    submitForm (ruleForm) {
      console.log(this.isFromStore)
      if (!this.isFromStore) {
        this.ruleForm.password = this.$md5(this.ruleForm.password)
        console.log(this.ruleForm.password)
      }
      // 验证码判断
      if (this.judgeCode) {
        this.$message.error('验证码有误')
      } else {
        // 表单验证
        this.$refs.ruleForm.validate(valid => {
          // console.log(valid)
          if (!valid) return 0
          login(this.ruleForm).then(res => {
            if (res.code === 20000) {
              this.$message.success('登录成功')

              // 账户密码保存操作
              if (this.rememberpwd) {
                // 保存帐号到localStorage
                setStore('user', this.ruleForm.username)
                // 保存密码到localStorage
                setStore('password', this.ruleForm.password)
              } else {
                removeStore('user')
                removeStore('password')
              }

              // 保存后台发来得 localStorage 保存至会话储存
              window.sessionStorage.setItem('token', res.data.USERTOKEN)
              // 2. 通过编程式导航跳转到后台主页，路由地址是 /Home_s ,/Home_t
              if (this.ruleForm.usertype === '1') {
                // console.log(res.data.eno, res.data.sCardNo)
                this.$emit('getSinfo', res.data.eno, res.data.sCardNo)
                this.$router.replace({ path: '/studentPage/stuSignup' })
              } else {
                this.$router.replace({ path: '/manageClass/allRoomsInfo' })
              }
            }
          }).catch((e) => {
            this.$message.error('登录失败')
          })
        })
      }
    },

    // 每次显示编辑界面前进行预处理
    handleEdit: function (message) {
      this.stuFormVisible = true
      if (message === '注册') {
        this.title = '注册账号'
        this.buttomValue = '获取邮箱验证码'
        this.method = '注册'
        this.form_label = '你的密码'

        // 初始化处理
        this.stuForm.sCardNo = ''
        this.stuForm.sCardType = ''
        this.stuForm.sUsername = ''
        this.stuForm.sPassword = ''
        this.stuForm.rStuPassword = ''
        this.stuForm.status = 0
        this.stuForm.code = ''
      } else if (message === '重置') {
        this.title = '找回密码'
        this.buttomValue = '获取邮箱验证码'
        this.method = '重置'
        this.form_label = '新的密码'

        // 初始化处理
        this.stuForm.sCardNo = this.ruleForm.username
        this.stuForm.sCardType = ''
        this.stuForm.sUsername = ''
        this.stuForm.sPassword = ''
        this.stuForm.rStuPassword = ''
        this.stuForm.status = 1
        this.stuForm.code = ''
      }
    },

    // 发送请求邮箱验证码
    getJudgeCode (stuForm) {
      this.$refs.stuForm.validate(valid => {
        if (valid) {
        //  60秒 倒计时获取验证码机制
          this.disabled = false
          getCode(stuForm).then(res => {
            // console.log(res)
          })
          this.countdown = 60
          const that = this // 定时器的this指向已发生改变， 需要用that代替
          var time = setInterval(function () {
            that.disabled = true
            that.countdown--
            that.buttomValue = '重新发送(' + that.countdown + 's)'
            if (that.countdown === 0) {
              that.disabled = false
              that.buttomValue = '重新获取'
              clearInterval(time)
            }
            // console.log(that.countdown)
          }, 1000)
        } else {
          return false
        }
      })
    },

    // 学生注册和找回密码
    submitStuForm (stuForm) {
      this.$refs.stuForm.validate(valid => {
        if (!valid) return false
        if (this.stuForm.sPassword === this.stuForm.rStuPassword) {
          getAccount(this.stuForm).then(res => {
            if (res.data.info === '注册成功') {
              this.$message.success('注册成功')
              clearInterval(this.time) // 关闭定时器 细节处理
              this.stuFormVisible = false
            } else if (res.data.info === '修改密码成功') {
              this.$message.success('找回密码成功')
            } else {
              this.$message.error('账号已注册，请勿重复注册')
            }
          }).catch((e) => {
            this.$message.error('网络请求失败')
          })
        } else {
          this.$message.error('输入的密码不一致!')
        }
      })
    },

    // 关闭编辑、添加弹出框
    closeDialog () {
      this.stuFormVisible = false
    }
  },
  computed: {
    judgeCode () {
      // 验证码判断 降低严格 不区分大小写
      // console.log(this.corCode.toString().toLowerCase())
      // console.log(this.loginCode.split('').toString().toLowerCase())
      return this.corCode.toString().toLowerCase() !== this.loginCode.split('').toString().toLowerCase()
    }
  },
  mounted () {
    // console.log(this.corCode.toString())
  }
}

</script>

<style lang="stylus" scoped>

  .login-wrap
    box-sizing: border-box
    width: 100%
    height: 100%
    padding-top 10%
    padding-bottom : 16%
    background-repeat: no-repeat
    background-position: center right
    background-size: 110%
    background-color #b3d4eb
    background-image: url(../../assets/images/back.png)
    .login-title
     width: 50vw
     height: 14vh
     text-align : center
     font-size : 3vh
     font-weight: 600
     margin -5vh auto auto auto
  .login-container
    border-radius: 10px
    margin: 0px auto
    width: 20vw
    padding: 30px 35px 15px 35px
    border: 1px solid #eaeaea
    text-align: left
    background: #FFF
    .gmu_logo
     position: relative
     display : block
     margin : -80px auto auto auto
     width: 5vw
     height: 10vh
  .title
    padding-top: 30px
    margin: 0px auto 40px auto
    text-align: center
    color: #505458
  .remember
    margin: 0px 0px 35px 0px
  .code-box
    text-align: right
  .codeimg
    height: 40px
  .code
    margin-left : 25px
  .registered
    margin-left : 80px
    height : 20px
    line-height : 0px
    font-size : 13px
  .forget
    font-size : 13px
    color : #505458
  .getJudgeCode
    margin-left : 20px
    font-size : 12px
    width : 100px
    height : 30px
    padding: 1px 7px 3px 7.5px
</style>
